/* dest.c */

#include <sys/types.h>
#include <sys/socket.h>
#include <stdio.h>
#include <time.h>

#define BUFLEN 512

int main(int argc, char*argv[]) {

	if (argc != 4) {
		printf("Illegal number of args");
		exit(1);
	} else {
		int dest_addr = argv[1];
		int dest_port = argv[2];
		int local_port = argv[3];
		
		//create socket
		int listen_socket, send_socket;
		int bytes_read, bytes_sent;
		char buf[BUFLEN];
		
		if ((listen_socket = socket(PF_INET, SOCK_DGRAM, 0)) == -1) {
			perror("Listen socket creation failed.");
			exit(1);
		} 
		
		if ((send_socket = socket(PF_INET, SOCK_DGRAM, 0)) == -1) {
			perror("Send socket creation failed.");
			exit(1);
		} 
		
		//bind listening and sending sockets
		struct sockaddr_in my_addr, send_addr;
		
		bzero(&my_addr, sizeof(my_addr));
		my_addr.sin_family = AF_INET;
                my_addr.sin_addr.s_addr = INADDR_ANY;
		my_addr.sin_port = htons(local_port);
		
		memset((char *) &send_addr, 0, sizeof(send_addr));
		send_addr.sin_family = AF_INET;
		send_sddr.sin.addr.s_addr = INADDR_ANY;
		send_addr.sin_port = htons(dest_port);
		
		if((bind(listen_socket,(struct sockaddr *)&my_addr, sizeof(my_addr)) == -1) ||
            bind(send_socket,(struct sockaddr *)&send_addr, sizeof(send_addr)) == -1) {
			perror("Bind sockets failed");
			exit(1);
		}
				
		//listens for packets on local socket	
		while (1) {
			dest_length = (int)sizeof(struct sockaddr_in);
			bytes_read = recvfrom(listen_socket, buf, BUFLEN, 0, (struct sockaddr *)&dest_addr, &dest_length);
			time_t clock = time(NULL);
			
			if(bytes_read > 0) {
				printf("recv - " + ctime(&clock));
			}
			send_length = (int)sizeof(struct sockaddr);
			bytes_sent = sendto(send_socket, buf, BUFLEN, 0, (struct sockaddr *)&send_addr, &send_length);
			if(bytes_sent > 0) {
                printf("sendto - " + ctime(&clock));
            }
		}
		
	}

	/*
	int sendto(int sockfd, const void *msg, int len, unsigned int flags,
	const struct sockaddr *to, socklen_t tolen);

	int recvfrom(int sockfd, void *buf, int len, unsigned int flags,
	struct sockaddr *from, int *fromlen);
	*/
	
	return 0;
	
}
